/*
 * @Author: xzy 1453077527@qq.com
 * @Date: 2025-08-21 11:11:57
 * @LastEditors: xzy 1453077527@qq.com
 * @LastEditTime: 2025-08-21 15:51:23
 * @Description:
 */
package com.xtedu.examproject.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.xtedu.examproject.entity.Menu;
import com.xtedu.examproject.entity.StudentExamRecordDTO;
import com.xtedu.examproject.entity.User;
import com.xtedu.examproject.service.MenuService;
import com.xtedu.examproject.service.StudentExamRecordService;
import com.xtedu.examproject.service.UserService;
import com.xtedu.examproject.util.MenuTreeBuilder;
import com.xtedu.examproject.util.RedisUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private MenuService menuService;
    private UserService userService;
    private StudentExamRecordService studentExamRecordService;

    public void init() {
        userService = new UserService();
        menuService = new MenuService();
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(req, resp);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        // 验证验证码
        if (!captchaCheck(req, resp)) {
            resp.sendRedirect("login");
            return;
        }

        // 验证登录信息
        if (!loginCheck(req, resp)) {
            resp.sendRedirect("login");
            resp.getWriter().println("登录失败");
        }
    }

    public void destroy() {
    }

    /**
     * 登录验证
     *
     * @param req  请求
     * @param resp 响应
     * @return 用户名密码是否正确
     */
    public Boolean loginCheck(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            //获取用户输入的用户名和密码
            String username = req.getParameter("phone");
            String password = req.getParameter("pwd");

            // 验证用户名和密码
            if (username.isEmpty() || password.isEmpty()) {
                resp.getWriter().println("用户名和密码不能为空!");
                return false;
            }

            // 根据用户名查询用户
            User user = userService.findUserByUsername(username);
            //用户输入密码加密
            String digestPassword = DigestUtil.sha256Hex(password);

            if (user.getName() == null) {
                resp.getWriter().println("用户不存在");
                return false;
            }
            if (!user.getPassword().equals(digestPassword)) {
                resp.getWriter().println("密码不正确");
                return false;
            }

            // 携带导航信息及用户角色ID
            List<Menu> menus = menuService.findMenusByRoleId(user.getRoleId());
            List<Menu> treeMenus = MenuTreeBuilder.buildMenuTree(menus);
            user.setMenus(treeMenus);
            System.out.println(treeMenus);

            // 将登录用户信息存储到session中
            HttpSession session = req.getSession();

            // 验证成功
            //添加用户身份验证，跳转到不同的页面
            //session.setAttribute("user", user);
            RedisUtil.setObject("session:" + session.getId(), user);
            RedisUtil.expire("session:" + session.getId(), 60 * 60 * 24);
            // 验证成功

            resp.sendRedirect("default");
            return true;
        } catch (Exception e) {
            req.getSession().setAttribute("errorMessage", "登录异常，请重试");
            req.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(req, resp);
            log("用户登录失败", e);
            return false;
        }
    }

    /**
     * 验证码验证
     *
     * @param req  请求
     * @param resp 响应
     * @return 输入的验证码是否正确
     */
    public Boolean captchaCheck(HttpServletRequest req, HttpServletResponse resp) {
        // 获取用户输入的验证码
        String userCaptcha = req.getParameter("userCaptcha").toUpperCase();

        // 获取session中的验证码
        HttpSession session = req.getSession();
        String captcha = (String) session.getAttribute("captcha");
        if (!(captcha != null && captcha.equals(userCaptcha))) {
            // 验证失败
            return false;
        }
        // 验证成功进行用户名和密码验证
        // 验证完成后移除session中的验证码（可选）
        session.removeAttribute("captcha");
        return true;
    }
}
